<template>
  <page-dialog
    :title="dialogInfo.title"
    v-model:visible="shows"
    :width="dialogInfo.width"
    :bt-loading="dialogInfo.btLoading"
    :bt-list="dialogInfo.btList"
  >
    <div class="dialog-table">
      <NewPageFilter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.searchBtn"
      >
        <template v-slot:filter-button>
          <div class="dialog-table-header">
            <div class="header-left">
              <div class="lable">产品名称：{{ info.commonName }}</div>
              <div class="lable">生产批号：{{ info.batchNumber }}</div>
            </div>
            <div class="header-right">
              <div class="scan-groups">
                <el-input
                  v-model="filterInfo.keyword"
                  :clearable="true"
                  placeholder="请输入个体码"
                  @keyup.enter="search"
                  @input="(e) => (filterInfo.keyword = validSe(e))"
                ></el-input>
                <el-button style="margin-left: 10px" @click="search"
                  >搜索</el-button
                >
              </div>
            </div>
          </div>
        </template>
      </NewPageFilter>
    </div>
    <dialog-table
      :refresh="tableInfo.refresh"
      :init-curpage="tableInfo.initCurpage"
      v-model:data="tableInfo.data"
      ref="depotTable"
      :api="tableInfo.api"
      :check-box="false"
      :tab-index="true"
      :pager="false"
      :listen-height="false"
      :query="filterInfo.query"
      :field-list="tableInfo.fieldList"
      :handle="tableInfo.handle"
      @handleEvent="handleEvent"
    />
    <chose-printer :visible="printerInfo.visible" @callBack="printerCallBack" />
  </page-dialog>
</template>

<script setup name="singleProductView">
import PageDialog from '@/components/PageDialog/index'

import {
  receivingDetailsCustomizeListAll,
  receivingPrintSingleQrCode,
} from '@/api/stock'
import { getCustomizeSetting } from '@/api/customize'
import DialogTable from '@/components/DialogTable/index'
import ChosePrinter from '@/components/ChosePrinter/index'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps({
  showDialog: {
    type: Boolean,
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  info: {
    type: Object,
    default: function () {
      return {}
    },
  },
  pageStatus: {
    type: Boolean,
  },
  id: {
    type: Number,
    default: 0,
  },
  receivingSourceId: {
    type: Number,
    default: -2,
  },
  infoStatus: {
    type: Number,
    default: 0,
  },
  isEstimationStockBusiness: {
    type: Number,
    default: 0
  },
  confirmStatus: {
    type: Number,
    default: 0
  }
})

// 过滤相关配置
const filterInfo = reactive({
  keyword: '',
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
      id: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: props.info.groupConcatIds,
      },
    },
    queryParams: { orderId: props.id, skipWithTable: 1 },
    customizeUserVO: {},
  },
  searchBtn: [{ slot: true, value: 'button' }],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  copyData: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '打印二维码',
        event: printSingleQrCode,
        show: proxy.$permission('receiving:printCode') && props.pageStatus,
      },
      {
        label: '撤回入库',
        event: showRevokable,
        show: proxy.$permission('receiving:revokable'),
        ifRender: ifRenderValue,
      },
      {
        label: '撤回入库并拒收',
        event: showRevokableAndRefuse,
        show: proxy.$permission('receiving:insertRevokeAndRefuse'),
        ifRender: ifRenderValue,
      },
    ],
  },
})
// 弹窗相关
const dialogInfo = reactive({
  title: '个体详情',
  width: '90%',
  btLoading: false,
  btList: [{ label: '关闭', event: handleClose, show: true }],
})
const printerInfo = reactive({
  visible: false,
  data: {},
})

const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emit('update:showDialog', newValue) // 更新父组件shows
  },
})

let obj = {
  price: {
    label: '单价',
    value: 'price',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('receiving:price'),
    show: false,
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('receiving:price'),
    show: false,
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('receiving:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
  defaultPrice: {
    label: '默认价格',
    value: 'defaultPrice',
    type: 'column',
    permission: !proxy.$permission('receiving:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()
function showRevokableAndRefuse(row) {
  //撤回
  receivingDetailsCustomizeListAll(filterInfo.query).then((res) => {
    if (res && res.success) {
      let data = res.data
      let item = data.find((item) => item.id === row.id)
      if (item.canInvalidCalcQty > 0) {
        shows.value = false
        emit('showRevokableAndRefuse', row.id)
      } else {
        proxy.$message({
          message: '无可撤回数量，请刷新数据',
          type: 'warning',
          duration: 3500,
          showClose: true,
        })
        return
      }
    }
  })
}

// 获取列表
function getList() {
  tableInfo.refresh = Math.random()
}
function search() {
  const search = filterInfo.keyword

  if (search) {
    tableInfo.data = tableInfo.copyData.filter((data) => {
      return Object.keys(data).some((key) => {
        if (key === 'qrCode') {
          return String(data[key]).indexOf(search) > -1
        } else if (key === 'uniqueCode') {
          return String(data[key]).indexOf(search) > -1
        } else if (key === 'factorySubCode') {
          return String(data[key]).indexOf(search) > -1
        } else if (key === 'factoryMainCode') {
          return String(data[key]).indexOf(search) > -1
        }
      })
    })
  } else {
    tableInfo.data = tableInfo.copyData
  }
}
function ifRenderValue(row) {
  return (
    props.receivingSourceId === -2 &&
    props.infoStatus === 3 &&
    row.isWithTable === 0 &&
    (props.isEstimationStockBusiness === 1 ? props.confirmStatus === 0 : true) &&
    row.canInvalidCalcQty > 0
  )
}
function showRevokable(row) {
  //撤回
  receivingDetailsCustomizeListAll(filterInfo.query).then((res) => {
    if (res && res.success) {
      let data = res.data
      let item = data.find((item) => item.id === row.id)
      if (item.canInvalidCalcQty > 0) {
        shows.value = false
        emit('showRevokable', row.id)
      } else {
        proxy.$message({
          message: '无可撤回数量，请刷新数据',
          type: 'warning',
          duration: 3500,
          showClose: true,
        })
        return
      }
    }
  })
}
function handleEvent(event, data) {
  switch (event) {
    case 'list':
      tableInfo.copyData = data
      break
  }
}
//打印单个二维码
function printSingleQrCode(row = undefined) {
  if (!row.qrCode) {
    proxy.$message({
      message: '没有生成二维码，不能打印',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  let ids = [row.id]
  if (ids.length > 0) {
    receivingPrintSingleQrCode(ids).then((resp) => {
      if (resp && resp.success) {
        printerInfo.visible = true
        printerInfo.data = resp.data
      }
    })
  }
}
function printerCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.data, printer)
  }
  printerInfo.visible = false
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emit('reset')
}
function getCustomize() {
  let param = {
    tableKey:
      'stockReceivingOrderSingleDetails-com.slip.spd.entity.vo.stock.ReceivingOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = res.data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      tableInfo.api = receivingDetailsCustomizeListAll
      getList()
    }
  })
}
</script>

<style scoped lang="scss">
:deep(.filter-item) {
  width: 100%;
}
.text-style {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.scan-groups {
  display: flex !important;
  align-items: center;
}
</style>
